import {getTicket} from "../../../../network/serversCampus";
import sha1 from 'sha1'

//生成随机字符串
export const randomString = (len?: number) => {
  len = len || 32;
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length;
  var pwd = '';
  for (var i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

interface ConfigParams {
  debug: boolean;
  appId: string;
  timestamp: number;
  nonceStr: string;
  signature: any;
  jsApiList: string[];
}

export async function getWxSDKParams(jsApiList: string[]): Promise<ConfigParams> {
  //具体查看：https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html
  try {
    const {ticket} = await getTicket('S-3333')
    const timestamp = new Date().getTime()
    const nonceStr = randomString(16)
    const url = window.location.href.split('#')[0]
    const signature = sha1(`jsapi_ticket=${ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${url}`)

    return {
      debug: false, // 开启调试模式,调用的所有 api 的返回值会在客户端 alert 出来，若要查看传入的参数，可以在 pc 端打开，参数信息会通过 log 打出，仅在 pc 端时才会打印。
      appId: 'wxe2f5257540ab7646', // 必填，公众号的唯一标识
      timestamp: timestamp, // 必填，生成签名的时间戳
      nonceStr: nonceStr, // 必填，生成签名的随机串
      signature: signature,// 必填，签名
      jsApiList: jsApiList // 必填，需要使用的 JS 接口列表,具体提供哪些请看说明网址
    }
  } catch (err) {
    throw new Error(err)
  }
}

export function concatParamsStr(obj:any) {
  let result = '';
  let item;
  for (item in obj) {
    if (obj[item] && String(obj[item])) {
      result += `&${item}=${encodeURIComponent(obj[item])}`;
    }
  }
  if (result) {
    result = '&' + result.slice(1);
  }
  return result;
}

export * from "./type";
